<template>
  <div class="login">
    <div class="login-con">
      <Card>
        <p slot="title">
          <span>{{title}}</span>
        </p>
        <Tabs :value="tab">
          <TabPane name="login">
            <Form class="form" ref="loginForm" :rules="loginRules" :model="loginForm" v-show="tab === 'login'">
              <FormItem prop="username" >
                <Input type="text" v-model="loginForm.username" placeholder="请输入用户名">
                  <Icon type="ios-person-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem prop="password">
                <Input type="password" v-model="loginForm.password" placeholder="请输入密码">
                  <Icon type="ios-lock-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem>
                <Button type="primary" :loading="loginLoading" :long="true" @click="login">登录</Button>
              </FormItem>
              <a @click="changeTab">没有账户？注册</a>
            </Form>
          </TabPane>
          <TabPane name="register">
            <Form class="form" ref="registerForm" :rules="registerRules" :model="registerForm" v-show="tab === 'register'">
              <FormItem prop="username" >
                <Input type="text" v-model="registerForm.username" placeholder="请输入用户名">
                  <Icon type="ios-person-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem prop="password">
                <Input type="password" v-model="registerForm.password" placeholder="请输入密码">
                  <Icon type="ios-lock-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem prop="repeatPassword">
                <Input type="password" v-model="registerForm.repeatPassword" placeholder="请再输入密码">
                  <Icon type="ios-lock-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem prop="userType">
                <Select v-model="registerForm.userType">
                  <Option :value="1">用户</Option>
                  <Option :value="2">厂商</Option>
                  <Option :value="3">物业</Option>
                </Select>
              </FormItem>
              <FormItem prop="verCode"  style="float: left; width: 50%">
                <Input type="text" v-model="registerForm.verCode" placeholder="请输入验证码">
                  <Icon type="ios-image" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <div style="float: right; width: 50%; display: flex; justify-content: center">
                <img :src="imageSrc" @click="captcha">
              </div>
              <FormItem style="overflow: hidden">
                <Button type="primary" :loading="registerLoading" :long="true" @click="register">注册</Button>
              </FormItem>
              <a @click="changeTab">已有账户？登录</a>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      const validateUsername = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('用户名不能为空'));
        } else {
          let form = new FormData();
          form.append("name", value);
          this.$requests.post("/user/check", form).then(res => {
            if (res.data.code === 0) {
              callback();
            } else {
              callback(new Error(res.data.msg));
            }
          })
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (value.length < 6) {
          callback(new Error('密码过于简单'));
        } else {
          callback();
        }
      };
      const validateRepeatPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (this.registerForm.password !== value) {
          callback(new Error('两次密码不一致'));
        } else {
          callback();
        }
      };
      return {
        title: "欢迎登录",
        tab: "login",
        // 登录信息
        loginForm: {
          username: "",
          password: "",
        },
        // 登录验证规则
        loginRules: {
          username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ]
        },
        // 登录加载
        loginLoading: false,
        // 注册表单
        registerForm: {
          username: "",
          password: "",
          repeatPassword: "",
          userType: 1,
          uuid: "",
          verCode: ""
        },
        // 验证码
        imageSrc: "",
        // 注册验证规则
        registerRules: {
          username: [
            {validator: validateUsername, trigger: 'blur'}
          ],
          password: [
            {validator: validatePass, trigger: 'blur'}
          ],
          repeatPassword: [
            {validator: validateRepeatPass, trigger: 'blur'}
          ],
          verCode: [
            { required: true, message: '验证码不能为空', trigger: 'blur' }
          ],
        },
        registerLoading: false,
      }
    },
    methods: {
      login() {
        const Base64 = require('js-base64').Base64;
        this.$refs["loginForm"].validate((valid) => {
          if (valid) {
            this.loginLoading = true;
            let form = new FormData();
            form.append("username", this.loginForm.username);
            form.append("password", Base64.encode(this.loginForm.password));
            this.$requests.post("/user/login", form).then(res => {
              if (res.data.code === 0) {
                this.$Message.success("登录成功");
                sessionStorage.setItem("token", res.data.data);
                setTimeout(() => {
                  this.$router.push({name: "index"});
                }, 1000)
              } else {
                this.$Message.error(res.data.msg);
              }
              setTimeout(() => {
                this.loginLoading = false;
              }, 500)
            })
          }
        })
      },
      register() {
        const Base64 = require('js-base64').Base64;
        this.$refs["registerForm"].validate((valid) => {
          if (valid) {
            this.registerLoading = true;
            let form = new FormData();
            form.append("username", this.registerForm.username);
            form.append("password", Base64.encode(this.registerForm.password));
            form.append("uuid", this.registerForm.uuid);
            form.append("verCode", this.registerForm.verCode);
            form.append("userType", this.registerForm.userType);
            this.$requests.post("/user/register", form).then(res => {
              if (res.data.code === 0) {
                this.$Message.success("注册成功");
                this.tab = "login";
              } else {
                this.$Message.error(res.data.msg);
              }
              this.captcha();
              setTimeout(() => {
                this.registerLoading = false;
              }, 500)
            })
          }
        })
      },
      changeTab() {
        if (this.tab === "login") {
          this.$refs["registerForm"].resetFields();
          this.captcha();
          this.tab = "register";
          this.title = "欢迎注册";
        } else {
          this.$refs["loginForm"].resetFields();
          this.tab = "login";
          this.title = "欢迎登录";
        }
      },
      captcha() {
        this.$requests.get("/captcha?r=" + new Date().getTime(), null).then(res => {
          if (res.data.code === 0) {
            this.imageSrc = "data:image/jpeg;base64," + res.data.data.image;
            this.registerForm.uuid = res.data.data.uuid;
          }
        })
      }
    }
  }
</script>

<style lang="less">
  .login {
    width: 100%;
    height: 100%;
    background: url("../assets/background.jpg");

    .login-con {
      position: absolute;
      left: 50%;
      top: 50%;
      -webkit-transform: translateY(-60%);
      transform: translateY(-60%);
      width: 400px;
      margin-left: -200px;

      .form {
        padding: 10px 0;

        .ivu-form-item {
          width: 100%;
        }
      }

      .ivu-tabs-bar {
        display: none;
      }

      a {
        float: right;
      }
    }
  }
</style>
